package com.jpexs.asdec.tools;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.InflaterInputStream;

import com.jpexs.asdec.SWFInputStream;

public class Uncompress {

	private void uncompress(InputStream is, OutputStream os) throws IOException {
		byte hdr[] = new byte[3];
		byte lengthBuf[] = new byte[4];
		is.read(hdr);
		String shdr = new String(hdr);
		if ((!shdr.equals("FWS")) && (!shdr.equals("CWS"))) {
			throw new IOException("Invalid SWF file");
		}
		int version = is.read();
		SWFInputStream sis = new SWFInputStream(is, version);
		sis.read(lengthBuf);
		if (hdr[0] == 'C') {
			sis = new SWFInputStream(new InflaterInputStream(is), version);
		}
		hdr[0] = 'F';
		os.write(hdr);
		os.write(version);
		os.write(lengthBuf);
		byte buf[] = new  byte[4096];
		while(true) {
			int bytesRead = sis.read(buf);
			if (bytesRead < 0) {
				break;
			}
			os.write(buf, 0, bytesRead);
		}
	}

	public void go(String srcPath, String destPath) throws IOException {
		FileInputStream fis = new FileInputStream(srcPath);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(destPath);
			uncompress(fis, fos);
		} finally {
			try {
				fis.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			throw new Exception("usage: "+Uncompress.class.getName()+" srcPath destPath");
		}
		Uncompress uu = new Uncompress();
		String srcPath = args[0];
		String destPath = args[1];
		System.out.println("uncompressing "+srcPath+" to "+destPath);
		uu.go(srcPath, destPath);
	}

}
